package com.lingxu.module.redList.controller;

import com.lingxu.base.common.api.vo.Result;
import com.lingxu.base.common.constant.LogType;
import com.lingxu.base.common.util.EasyExcelUtils;
import com.lingxu.base.common.util.UUID32Generator;
import com.lingxu.base.config.LogInfoHandler;
import com.lingxu.base.system.manage.vo.LoginUser;
import com.lingxu.module.collection.service.ICollectionMonitorService;
import com.lingxu.module.message.entity.UserMessage;
import com.lingxu.module.message.mapper.MessageMapper;
import com.lingxu.module.redList.entity.ParamsDTO;
import com.lingxu.module.redList.entity.RedList;
import com.lingxu.module.redList.entity.RedListApply;
import com.lingxu.module.redList.entity.RedListTemp;
import com.lingxu.module.redList.service.RedListApplyService;
import com.lingxu.module.redList.service.RedListService;
import com.lingxu.module.redList.service.RedListTempService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Title: RedListController
 * @Package: com.lingxu.module.redList.controller
 * @Author: ysj闫世杰
 * @Email: 1105324813@qq.com
 * @Date: Created in 2023/6/15 14:55
 * @Description: 红名单管理
 * @Version: 1.0.0
 */
@Slf4j
@RestController
@RequestMapping(value = "/redList")
public class RedListController {

    @Autowired
    private RedListService redListService;
    @Autowired
    private RedListApplyService redListApplyService;
    @Autowired
    private RedListTempService redListTempService;
    @Autowired
    private ICollectionMonitorService collectionMonitorService;

    @Autowired
    private MessageMapper messageMapper;

    /**
     * @Author ysj闫世杰
     * @Description 导入Excel
     * @Date 2023/6/15 16:12
     * @Param: file
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @RequestMapping(value = "/importRedList")
    public Result importRedList(MultipartFile file){
        List<RedList> redLists = EasyExcelUtils.importExcel(file, 0, 1, RedList.class);
        if(redLists!=null && redLists.size()>0){
            for(RedList redList:redLists){
                if(StringUtils.isBlank(redList.getCityCode()) && StringUtils.isNotBlank(redList.getCityName())){
                    String citycode = collectionMonitorService.getRegionByCityName(redList.getCityName());
                    if(StringUtils.isNotBlank(citycode)){
                        redList.setCityCode(citycode);
                    }
                }
            }
        }
        redListService.saveBatch(redLists);
        String content = "通过系统导入红名单信息，共计" + redLists.size() + "条记录";
        new LogInfoHandler().setLogInfoHandler(LogType.LOG_RED_LIST_UPDATE,content);
        return Result.ok("操作成功");
    }

    //新增
    @RequestMapping(value = "/addRedList")
    public Result addRedList(@RequestBody RedListApply apply){
        //校验身份证唯一性
        //审批表状态校验
        int i = redListApplyService.findExistByIdCard(apply.getIdcard());
        if(i > 0){
            return Result.error("该人员已存在待审批记录！");
        }
        int ii = redListService.findExistByIdCard(apply.getIdcard());
        if(ii > 0){
            return Result.error("该身份证号码已被登记为红名单人员！");
        }
        //记录表唯一性校验
        String recordId = UUID32Generator.generate();
        apply.setRecordId(recordId);
        apply.setCreateTime(new Date());
        apply.setApprovalStatus("0");
        apply.setSource("1");
        redListApplyService.save(apply);
        String content = "通过系统录入红名单信息等待审批";
        new LogInfoHandler().setLogInfoHandler(LogType.LOG_RED_LIST_UPDATE,content);
        return Result.ok("操作成功");
    }

    /**
     * @Author ysj闫世杰
     * @Description 修改
     * @Date 2023/6/15 16:42
     * @Param: redList
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @RequestMapping(value = "updateRedList")
    public Result updateRedList(@RequestBody RedListApply apply){
        //查询是否已申请修改
        int row = redListApplyService.findExist(apply.getRecordId());
        if(row > 0){
            return Result.error("该记录当前为待审批状态！");
        }
        String content = "修改了红名单信息，修改记录人员为：【"+ apply.getName() +"】，等待审核。";
        //修改信息需要推送审核
        apply.setCreateTime(new Date());
        apply.setApprovalStatus("0");//申请
        apply.setSource("2");
        redListApplyService.save(apply);
        new LogInfoHandler().setLogInfoHandler(LogType.LOG_RED_LIST_UPDATE,content);
        return Result.ok("操作成功");
    }

    //删除
    @RequestMapping(value = "/deleteRedList")
    public Result deleteRedList(String ids,String names){
        String[] arr = ids.split(",");
        for(String s : arr){
            RedList redList = new RedList();
            redList.setId(s);
            redList.setIsDel("1");
            redListService.updateById(redList);
            //同时删除申请记录表
            redListApplyService.removeById(s);
        }
        String content = "删除了红名单信息，删除记录人员为：【" + names +"】";
        new LogInfoHandler().setLogInfoHandler(LogType.LOG_RED_LIST_UPDATE,content);
        return Result.ok("操作成功");
    }

    /**
     * @Author ysj闫世杰
     * @Description 查询
     * @Date 2023/6/15 16:42
     * @Param: limit
     * @Param: page
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @RequestMapping(value = "/findRedList")
    public Result findRedList(@RequestBody ParamsDTO dto){
        if(!StringUtils.isEmpty(dto.getName())){
            String s = "】通过查询条件【"+dto.getKeyWord()+"】";
            if(!StringUtils.isEmpty(dto.getKeyWord())){
                String content = "在【"+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + s + "，查询了红名单信息";
                new LogInfoHandler().setLogInfoHandler(LogType.LOG_RED_LIST_WARNING,content);
            }
        }
        return redListService.findRedList(dto);
    }


    /**
     * @Author ysj闫世杰
     * @Description 查询申请列表
     * @Date 2023/6/20 9:17
     * @Param: limit
     * @Param: page
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @RequestMapping(value = "/findRedListApplyData")
    public Result findRedListApplyData(Integer limit ,Integer page,String status,String cityCode){
        String content = "在【"+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) +"】查询了红名单申请信息列表";
        new LogInfoHandler().setLogInfoHandler(LogType.LOG_RED_LIST_FIND,content);
        return redListApplyService.findRedListApplyData(limit,page,status,cityCode);
    }

    //审批
    @RequestMapping(value = "updateApproval")
    public Result updateApproval(@RequestBody List<RedListApply> applyList){
        LoginUser user =  (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String createBy = user.getId();
        String flag = "";
        Date date = new Date();
        for(RedListApply apply : applyList){
            apply.setApprovalTime(date);
            boolean i = redListApplyService.updateById(apply);
            if(i){
                if("1".equals(apply.getApprovalStatus())){
                    //同意后更新红名单数据表
                    RedList redList = new RedList();
                    redList.setName(apply.getName());
                    redList.setWorkOrg(apply.getWorkOrg());
                    redList.setIdcard(apply.getIdcard());
                    redList.setCityName(apply.getCityName());
                    redList.setCityCode(apply.getCityCode());
                    redList.setUpdateTime(date);
                    redList.setCadresLev(apply.getCadresLev());
                    redList.setId(apply.getRecordId());
                    boolean ii = redListService.updateById(redList);
                    if(ii) {
                        flag = "修改";
                        String content = "在【"+ new SimpleDateFormat("yyyy-MM-dd").format(date) +"】审批通过修改红名单信息";
                        new LogInfoHandler().setLogInfoHandler(LogType.LOG_RED_LIST_UPDATE,content);
                    } else {
                        //新增
                        RedList redList2 = new RedList();
                        redList2.setName(apply.getName());
                        redList2.setWorkOrg(apply.getWorkOrg());
                        redList2.setIdcard(apply.getIdcard());
                        redList2.setCityName(apply.getCityName());
                        redList2.setCityCode(apply.getCityCode());
                        redList2.setUpdateTime(new Date());
                        redList2.setCadresLev(apply.getCadresLev());
                        redList2.setId(apply.getRecordId());
                        redList2.setCreateBy(createBy);
                        redList2.setType("系统录入");
                        boolean iii = redListService.save(redList2);
                        if(iii){
                            flag = "新增";
                            String content = "在【"+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) +"】审批通过新增红名单信息";
                            new LogInfoHandler().setLogInfoHandler(LogType.LOG_RED_LIST_UPDATE,content);
                        }
                    }
                    //保存用户消息表通知审批完成
                    UserMessage message = new UserMessage();
                    message.setUserId(createBy);
                    message.setRecordId(apply.getId());
                    message.setContent("您提交的"+ flag +"红名单人员【" +apply.getName()+ "】的信息审批已通过！");
                    messageMapper.insert(message);
                }else {
                    //保存用户消息表通知审批完成
                    UserMessage message = new UserMessage();
                    message.setUserId(createBy);
                    message.setRecordId(apply.getId());
                    message.setContent("您提交的新增或修改红名单人员【" +apply.getName()+ "】的信息已被拒绝，请重新提交申请！");
                    messageMapper.insert(message);

                    String content = "在【"+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) +"】审批拒绝"+ flag +"红名单信息";
                    new LogInfoHandler().setLogInfoHandler(LogType.LOG_RED_LIST_UPDATE,content);
                }
            }
        }
        return Result.ok("操作成功");
    }

    /**
     * @Author ysj闫世杰
     * @Description 提供查询红名单接口服务
     * @Date 2023/6/19 16:15
     * @Param: keyWord
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @RequestMapping(value = "/openFindRedListApi")
    public Result openFindRedListApi(String keyWord){
        return redListService.openFindRedListApi(keyWord);
    }


    /**
     * @Author ysj闫世杰
     * @Description 导出红名单
     * @Date 2023/6/25 11:35
     * @Param: response
     * @return void
     **/
    @RequestMapping(value = "/exportRedList")
    public void exportRedList(HttpServletResponse response,String cityCode){
        redListService.exportRedList(response,cityCode);
    }

    /**
     * @Author ysj闫世杰
     * @Description 下载模板
     * @Date 2023/6/25 11:36
     * @Param:
     * @return void
     **/
    @RequestMapping(value = "/exportMode")
    public void exportMode(HttpServletResponse response){
        redListService.exportMode(response);
    }

    /**
     * @Author ysj闫世杰
     * @Description 查询红名单日志
     * @Date 2023/6/25 15:33
     * @Param: startTime
     * @Param: endTime
     * @Param: limit
     * @Param: page
     * @Param: type
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @RequestMapping(value = "/findRedListLog")
    public Result findRedListLog(String startTime,String endTime,Integer limit,Integer page,String type){
        return redListService.findRedListLog(startTime,endTime,limit,page,type);
    }


    /**
     * @Author ysj闫世杰
     * @Description 对比红名单人员并导出Excel
     * @Date 2023/6/25 16:22
     * @Param: file
     * @Param: response
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @RequestMapping(value = "/compareToRedList")
    public void compareToRedList(MultipartFile file, HttpServletRequest request, HttpServletResponse response, String userId, String realName, String userName){
        List<RedListTemp> redLists = EasyExcelUtils.importExcel(file, 0, 1, RedListTemp.class);
        redListTempService.saveBatch(redLists);
        redListService.compareToRedList(response,request,userId,realName,userName);
    }

    /**
     * @Author ysj闫世杰
     * @Description 查询待审批红名单数量
     * @Date 2023/7/24 15:09
     * @Param: userId
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @RequestMapping(value = "/findNeedApprovalCount")
    public Result findNeedApprovalCount(@RequestBody ParamsDTO dto){
        return redListService.findNeedApprovalCount(dto);
    }

    @RequestMapping(value = "/findNeedApprovalList")
    public Result findNeedApprovalList(Integer page,Integer limit){
        return redListService.findNeedApprovalList(page,limit);
    }

    @RequestMapping(value = "findInfosById")
    public Result findInfosById(String id){
        return Result.ok(redListApplyService.getById(id),"查询成功");
    }
}
